<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节流</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: rgb(143, 118, 118);
            text-align: center;
            line-height: 100px;
            color: aliceblue;
        }
    </style>
</head>

<body>
    <div></div>

    <script>
        const div = document.querySelector('div')

        // 节流:一段时间内触发某个事件,只执行第一次
        let num = 1
        function mouseMove() {
            div.innerHTML = num++
            console.log(num, '节流');
        }

        // 封装节流函数
        function throttle(fn, t) {
            let timer = null
            return function () {
                if (!timer) {
                    timer = setTimeout(() => {
                        fn() // 调用函数
                        // 清空定时器
                        timer = null
                    }, t)
                }
            }
        }

        div.addEventListener('mousemove', throttle(mouseMove, 3000))
    </script>
</body>

</html>